package cn.tianjindong.blog_manager.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.tianjindong.blog.common.pojo.PageView;
import cn.tianjindong.blog.pojo.BlogManager;
import cn.tianjindong.blog.pojo.BlogNotice;
import cn.tianjindong.blog_manager.service.NoticeService;

@Controller
public class NoticeController {

	@Autowired
	private NoticeService noticeService;

	/**
	 * 前往公告管理页面
	 * 
	 * @return
	 */
	@RequestMapping("/notice.html")
	public String toNoticePage(Model model, @RequestParam(defaultValue = "1") Integer currentPage,
			@RequestParam(defaultValue = "8") Integer countItem) {
		PageView<BlogNotice> pageView = noticeService.getNoticePageView(currentPage, countItem);
		model.addAttribute("pageView", pageView);
		return "/notice";
	}

	/**
	 * 增加公告
	 * 
	 * @param notice
	 * @return
	 */
	@RequestMapping("/notice/add.action")
	public String addNotice(HttpSession session, BlogNotice notice) {
		BlogManager user = (BlogManager) session.getAttribute("user");
		if (user != null) {
			noticeService.addNotice(notice, user.getId());
			return "redirect:/notice.html";
		} else {
			return "redirect:/login.html";
		}
	}

	/**
	 * 删除“公告”
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/notice/delete/{id}.action")
	public @ResponseBody String deleteNotice(@PathVariable Long id) {
		noticeService.deleteNoticeById(id);
		return null;
	}

	/**
	 * 前往公告的更新页面
	 * 
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping("/notice/update/{id}.html")
	public String toUpdateNoticePage(Model model, @PathVariable Long id) {
		BlogNotice notice = noticeService.getNoticeById(id);
		model.addAttribute("notice", notice);
		return "/update-notice";
	}

	/**
	 * 更新公告
	 * 
	 * @param notice
	 * @return
	 */
	@RequestMapping("/notice/update.action")
	public String updateNotice(BlogNotice notice) {
		noticeService.updateNotice(notice);
		return "redirect:/notice.html";
	}

	/**
	 * 进行公告的激活或作废工作
	 * @param id
	 * @param tab 标志此动作为激活还是作废，激活（tab==1）或作废请求(tab==0)
	 * @return
	 */
	@RequestMapping("/notice/activate/{tab}/{id}.action")
	public @ResponseBody String activateNotice(@PathVariable Long id, @PathVariable Integer tab) {
		noticeService.updateNoticeTab(id,tab);
		return null;
	}

}
